package cn.choujay.tlias.filter;

import cn.choujay.tlias.common.Result;
import cn.choujay.tlias.utils.JWTUtil;
import com.alibaba.fastjson2.JSON;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter("*")
public class LogInFilter implements Filter {
    @Resource
    private JWTUtil jwtUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
        log.info("过滤器初始化.......");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
//        response.addHeader("Access-Control-Allow-Headers", "token");
        String url = request.getRequestURI();
        //
        if (request.getMethod().equals("OPTIONS")) {
            filterChain.doFilter(request, response);
            String token = request.getHeader("token");
            log.info("预检请求，直接结束");
            return;
        }
        if (url.contains("/emp/login") || url.contains("/emp/check")) {
            //response.addHeader("Access-Control-Allow-Headers", "token");
            filterChain.doFilter(request, response);
            return;
        }
        //获取请求头中的令牌token
        String token = request.getHeader("token");
        log.info("令牌为：token:{}", token);
        if (!StringUtils.hasLength(token)) {
            log.error("token 不存在");
            Result result = Result.error("NOT_LOGIN");
            //把 Result对象转化为JSON字符串
            String json = JSON.toJSONString(result);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);
            return;
        }

        try {
            Claims claims = jwtUtil.parseJwt(token);
        } catch (Exception e) {
            log.info("令牌解析失败!");

            Result responseResult = Result.error("NOT_LOGIN");
            //把Result对象转换为JSON格式字符串 (fastjson是阿里巴巴提供的用于实现对象和json的转换工具类)
            String json = JSON.toJSONString(responseResult);
            response.setContentType("application/json;charset=utf-8");
            //响应
            response.getWriter().write(json);
            return;

        }
        filterChain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
        log.info("过滤器摧毁.......");
    }
}
